package com.stp.dtl645;

import com.stp.util.HexConverter;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class Dlt6452007Byte {
    public static void main(String[] args) {
        //读取正向有功电脑数据块模拟
        String hexStr = "FEFEFEFE6852121316072268911833323433644A3433834B333388583333BB7733336B5B33334E16";
        hexStr = removePreposeFrame(hexStr);
        byte[] bytes = HexConverter.hexString2ByteArray(hexStr);
        //获取地址号
        Stack<String> stack = new Stack<>();
        for (int i = 1; i <= Dlt645Frame.ADDRESS_FIELD_LEN; i++) {
            String s = Integer.toHexString(bytes[i]);
            if(s.length() == 1){
                s = String.format("%02d", Integer.parseInt(s));
            }
            stack.push(s);
        }
        StringBuilder eleMeterId = new StringBuilder();
        while (!stack.isEmpty()) {
            String byteStr = stack.pop();
            eleMeterId.append(byteStr);
        }
        /**
         * 获取数据标识
         * 68 52 12 13 16 07 22 68 91 18 33 32 34 33 64 4A 34 33 83 4B 33 33 88 58 33 33 BB 77 33 33 6B 5B 33 33 4E 16
         * 0  1  2  3  4  5  6  7  8  9  10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
         */
        List<String> list2 = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            list2.add(Integer.toHexString(bytes[bytes.length - 3 -(bytes[9] - 4) - i] - 0x33));
        }
        //4字节的数据标识
        String[] DTID = list2.toArray(new String[list2.size()]);
        StringBuilder dataIdentification = new StringBuilder();
        for (int i = 0; i < DTID.length; i++) {
            if (DTID[i].length() == 1) {
                DTID[i] = String.format("%02d", Integer.parseInt(DTID[i]));
            } else if (DTID[i].length() == 8) {
                DTID[i] = "FF";
            }
            dataIdentification.append(DTID[i]);
        }
        System.out.println(dataIdentification);
    }

    /**
     * 删除前置帧
     * @param hexString
     * @return
     */
    public static String removePreposeFrame(String hexString){
        if(hexString.contains("FEFEFEFE")){
            hexString = hexString.replaceAll("FEFEFEFE","");
        } else if (hexString.contains("fefefefe")) {
            hexString = hexString.replaceAll("fefefefe","");
        }
        return hexString;
    }
}
